import axios, { AxiosError } from "axios"
import { catchError, defer, ignoreElements, map, merge, timer } from "rxjs"

export class WpsAirScriptCaller
{
    constructor(
        private token: string,
        private scriptUrl: string
    ){}

    /**
     * 调用wps云中的函数并返回结果
     * @param contextData 
     * @returns 
     */
    getRawScriptResultWithContextObs(contextData: IWpsAirScriptContext)
    {
        let maxRetry = 10
        let currentRetryCount = 0
        return defer(() => axios.post(this.scriptUrl, {context: contextData}, {
            headers: {
                "Content-Type": "application/json",
                "AirScript-Token": this.token
            }
        })).pipe(
            catchError((err,baseObs) =>
            {
                currentRetryCount ++
                if(currentRetryCount > maxRetry)
                {
                    console.log(`AxiosError BUT retry max(${maxRetry})`)
                    throw err
                }
                if(err instanceof AxiosError)
                {
                    console.log(`WpsAirScriptCaller network error ${err.status}`)
                    console.log(err.response?.data)
                    return merge(timer(10e3).pipe(ignoreElements()), baseObs, 1)
                }
                throw err
            }),
            map(v => <IWpsAirScriptResultRaw>v.data)
        )
    }
}

export interface IWpsAirScriptContext
{
    argv?: {[x:string]: any}
    sheet_name?: string
    range?: string
    link_from?: string
    db_active_view?: string
    db_selection?: string
}

export interface IWpsAirScriptResultRaw {
    data:{
        logs:   IWpsAirScriptResultRawLog[];
        result: any;
    };
    error:  string;
    status: string;
}

export interface IWpsAirScriptResultRawLog {
    filename:  string;
    timestamp: string;
    unix_time: number;
    level:     string;
    args:      string[];
}